import os
from pathlib import Path
from typing import Dict, Any
import yaml  
from audio_pkg.models.configdata import *

'''
将配置文件加载到对应的数据模型中
'''
class LoadConfigData:
    def __init__(self, config_path:Path):
        self.config_path = config_path
    def handle(self,data):
            api=APIConfig(
                API_KEY=data["API_KEY"],
                SECRET_KEY=data["SECRET_KEY"],
                TOKEN_URL=data["TOKEN_URL"]
            )
            urls=TaskURLConfig(
                CREATE_TASK_URL=data["CREATE_TASK_URL"],
                QUERY_TASK_URL=data["QUERY_TASK_URL"]
            )
            voice=VoiceParamConfig(
                AUDIO_FORMAT=data["AUDIO_FORMAT"],
                DEFAULT_AUDIO_FORMAT=data["DEFAULT_AUDIO_FORMAT"],
                SPEED_VOLUME_PITCH_RANGE=tuple(data["SPEED_VOLUME_PITCH_RANGE"]),  # 转换为元组
                DEFAULT_SPEED=data["DEFAULT_SPEED"],
                DEFAULT_VOLUME=data["DEFAULT_VOLUME"],
                DEFAULT_PITCH=data["DEFAULT_PITCH"],
                CHOICES_VOICE=data["CHOICES_VOICE"],
                DEFAULT_VOICE=data["DEFAULT_VOICE"],
                ENABLE_SUBTITLE_CHOICES=data["ENABLE_SUBTITLE_CHOICES"],
                DEFAULT_ENABLE_SUBTITLE=data["DEFAULT_ENABLE_SUBTITLE"],
                DEFAULT_TIMES=data["DEFAULT_TIMES"],
                DEFAULT_DELAY=data["DEFAULT_DELAY"]
            )
            
            resource=ResourceDirectory(
                DEFAULT_OUTPUT = self.config_path / "audio_output",
                DEFAULT_TASK_JSON = self.config_path / "task_responses.json"
            )
        
            mime_map=data["MIME_TO_EXTENSION"]

            return AppConfig(
                api=api,
                urls=urls,
                voice=voice,
                mime_map=mime_map,
                resource=resource
            )
    

class ConfigLoader:
    defult_config = "default_config.yaml"

    def __init__(
            self,loader_data:LoadConfigData,
            app_name: str = "audiotts", 
            config_name: str = "config.yaml",
    ):
        """
        初始化 ConfigLoader。

        :param app_name: 应用名称，用于生成用户目录的配置路径（如 ~/.config/myapp）
        :param config_name: 配置文件名（如 config.yaml）
        """
        self.loader_data = loader_data
        self.app_name = app_name
        self.config_name = config_name

    def _get_user_config_path(self) -> Path:
        """
        获取用户目录下的配置文件路径。

        :return: 用户目录下的配置文件路径
        """
        system = os.name
        if system == "nt":  # Windows
            config_dir = Path.home() / "AppData" / "Local" / self.app_name
        else:  # Linux/macOS
            config_dir = Path.home() / ".config" / self.app_name
        return config_dir / self.config_name

    def _get_project_config_path(self) -> Path:
        """
        获取项目目录下的配置文件路径。

        :return: 项目目录下的配置文件路径
        """
        current_dir = Path(__file__).resolve().parent

        return current_dir / self.defult_config

    def _get_current_config_path(self) -> Path:
        """
        获取当前目录下的配置文件路径。

        :return: 当前目录下的配置文件路径
        """
        return Path.cwd() / self.config_name

    def load_config(self) -> AppConfig:
        """
        按照优先级加载配置文件。

        :return: 配置内容（字典形式）
        """
        # 优先级顺序：用户目录 > 项目目录 > 当前目录
        config_paths = [
            self._get_user_config_path(),
            self._get_project_config_path(),
            self._get_current_config_path(),
        ]

       
        for path in config_paths:
            if path and path.exists():
        
                with open(path, "r", encoding="utf-8") as file:
                    data = yaml.safe_load(file)
                    return self.loader_data.handle(data)

        raise FileNotFoundError("未找到配置文件！")

    def save_config(self, config: Dict[str, Any], path: Path = None):
        """
        保存配置文件。

        :param config: 配置内容（字典形式）
        :param path: 保存路径，默认为用户目录
        """
        if path is None:
            path = self._get_user_config_path()
        path.parent.mkdir(parents=True, exist_ok=True)  # 确保目录存在
        with open(path, "w", encoding="utf-8") as file:
            yaml.safe_dump(config, file)
        print(f"配置文件已保存：{path}")